package com.ruoyi.project.setting.aspect;

import com.ruoyi.project.setting.security.LoginUser;
import com.ruoyi.project.setting.security.utils.UserUtils;
import com.ruoyi.common.annotation.SysLog;
import com.ruoyi.common.exception.DemoModeException;
import com.ruoyi.framework.config.properties.CommonPropertis;
import com.ruoyi.project.monitor.entity.SysOperLog;
import com.ruoyi.project.monitor.syslog.SysLogUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 操作日志记录处理
 *
 * @author ruoyi
 */
@Aspect
@Order
@Slf4j
@Component
@RequiredArgsConstructor
public class SysLogAspect {

    private final CommonPropertis commonPropertis;

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.ruoyi.common.annotation.SysLog)")
    public void logPointCut() {
    }

    @Around("@annotation(sysLog)")
    public Object aroundSysLog(ProceedingJoinPoint point, SysLog sysLog) throws Throwable {
        if (commonPropertis.isDemoEnabled()) {
            throw new DemoModeException("演示模式");
        }
        return point.proceed();
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        SysOperLog sysOperLog = new SysOperLog();
        LoginUser loginUser = null;
        try {
            loginUser = UserUtils.currentLoginUser();
        } catch (Exception e) {
            log.info("无操作人员");
        }
        // 设置操作人类别、名称
        if (loginUser != null) {
            sysOperLog.setOperatorType(loginUser.getSysUser().getSocialCode());
            sysOperLog.setOperName(loginUser.getSysUser().getUserName());
            sysOperLog.setOperLocation(loginUser.getLoginLocation());
        }

        SysLogUtils.me().recordOperLog(joinPoint, jsonResult, sysOperLog);
    }
}
